package com.sntk.organauthomanager.application.controller;

import com.alibaba.fastjson.JSON;
import com.sntk.organauthomanager.application.dto.*;
import com.sntk.organauthomanager.application.service.UserApplicationService;
import com.sntk.organauthomanager.infrastructure.session.LoginSessionInfo;
import com.sntk.organauthomanager.infrastructure.validation.Insert;
import com.sntk.organauthomanager.infrastructure.validation.Update;
import com.sntk.organauthomanager.infrastructure.validation.Validation;
import com.sntk.organauthomanager.query.UserQuery;
import com.sntk.organauthomanager.query.param.UserCondition;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.validation.BindingResult;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpSession;
import java.util.List;

/**
 * @ClassName: UserController
 * @author: wgchao
 * @createTime: 2020/7/21 10:08 AM
 * @Description: TODO
 */
@RestController
@RequestMapping("/sinohis/osm/external/sys/user")
@Api(value="UserController",tags={"用户管理"})
public class UserController {
    @Autowired
    private UserApplicationService userApplicationService;
    @Autowired
    private UserQuery userQuery;

    @PostMapping
    @ApiOperation(value="添加用户")
    public ResponseData addUserToOrgan(@ApiParam(name="creator",value="用户信息",required=true)
                                           @RequestBody @Validated(value = {Insert.class}) UserCreator creator, BindingResult result, HttpSession httpSession){
        List<?> l = Validation.getValidation(result);
        if(l.size() != 0) {
            return ResponseData.error(JSON.toJSONString(l));
        }
        userApplicationService.addUserToOrgan(creator, LoginSessionInfo.generate(httpSession).getOperator());
        return ResponseData.success();
    }

    @PutMapping
    @ApiOperation(value="修改用户信息")
    public ResponseData modifyOrganInfo(@ApiParam(name="userDTO",value="用户信息",required=true)
                                        @RequestBody @Validated(value = {Update.class}) UserDTO userDTO, BindingResult result, HttpSession httpSession){
        List<?> l = Validation.getValidation(result);
        if(l.size() != 0) {
            return ResponseData.error(JSON.toJSONString(l));
        }
        userApplicationService.modifyUserInfo(userDTO, LoginSessionInfo.generate(httpSession).getOperator());
        return ResponseData.success();
    }

    @DeleteMapping("/{uname}")
    @ApiOperation(value="删除用户")
    public ResponseData removeUser(@ApiParam(name="uname",value="账户名",required=true)
                                    @PathVariable String uname, HttpSession httpSession){
        userApplicationService.removeUser(uname, LoginSessionInfo.generate(httpSession).getOperator());
        return ResponseData.success();
    }

    @GetMapping("/page/condition")
    @ApiOperation(value="分页条件查询用户信息")
    public ResponseData<PageData<UserVO>> searchOrgansOfConditions(@ApiParam(name="userCondition",value="分页查询条件",required=true)
                                                                           UserCondition userCondition, HttpSession httpSession){
        PageData<UserVO> voPageData = userQuery.searchUsersOfConditions(userCondition, LoginSessionInfo.generate(httpSession).getOperatorInfo());
        return ResponseData.success().setData(voPageData);
    }

    @GetMapping
    @ApiOperation(value="查询用户信息")
    public ResponseData<UserVO> searchUser(@ApiParam(name="uname",value="账户名",required=true) String uname){
        UserVO userVO = userQuery.searchUser(uname);
        return ResponseData.success().setData(userVO);
    }

    @GetMapping("/login")
    @ApiOperation(value="查询登陆用户信息")
    public ResponseData<UserVO> searchLoginUser(HttpSession httpSession){
        OperatorInfo operatorInfo = LoginSessionInfo.generate(httpSession).getOperatorInfo();
        return ResponseData.success().setData(userQuery.searchUser(operatorInfo));
    }

    @PutMapping("/reset/{uname}/pwd/{newpwd}")
    @ApiOperation(value="管理员重置用户密码密码")
    public ResponseData resetPassword(@ApiParam(name="uname",value="账户名",required=true)
                                          @PathVariable String uname,
                                      @ApiParam(name="newpwd",value="新密码",required=true)
                                      @PathVariable String newpwd, HttpSession httpSession){
        userApplicationService.resetPassword(uname, newpwd, LoginSessionInfo.generate(httpSession).getOperatorInfo());
        return ResponseData.success();
    }

    @PutMapping("/own/reset/pwd")
    @ApiOperation(value="账户修改自己的密码")
    public ResponseData modifyOwnPassword(@ApiParam(name="userPwd",value="用户密码信息",required=true)
                                              @RequestBody @Validated(value = {Update.class}) UserPwd userPwd,
                                          BindingResult result, HttpSession httpSession){
        List<?> l = Validation.getValidation(result);
        if(l.size() != 0) {
            return ResponseData.error(JSON.toJSONString(l));
        }
        userApplicationService.modifyOwnPassword(userPwd, LoginSessionInfo.generate(httpSession).getOperatorInfo());
        return ResponseData.success();
    }

    /**
     * 为用户分配角色
     * @param userRolesDTO
     * @param result
     * @param httpSession
     * @return
     */
    @PostMapping("/assignRolesToUser")
    @ApiOperation(value="为用户分配角色")
    public ResponseData assignRolesToUser(@ApiParam(name="userRolesDTO",value="用户的角色信息",required=true)
                                          @RequestBody UserRolesDTO userRolesDTO,
                                          BindingResult result,
                                          HttpSession httpSession){
        List<?> l = Validation.getValidation(result);
        if(l.size() != 0) {
            return ResponseData.error(JSON.toJSONString(l));
        }
        userApplicationService.assignRolesToUser(userRolesDTO.getUname(),userRolesDTO.getRoleCodes(),LoginSessionInfo.generate(httpSession).getOperator());
        return ResponseData.success();
    }

    //查询机构下的可用用户
    @GetMapping("/all/organ")
    @ApiOperation(value="查询机构下可用的用户信息")
    public ResponseData<List<UserDTO>> searchUserOfOrgan(@ApiParam(name="organNumber",value="机构编号",required=false) String organNumber,
                                                         HttpSession httpSession){
        List<UserDTO> userDTOs = userQuery.
                searchUserOfOrgan(StringUtils.isEmpty(organNumber) ? LoginSessionInfo.generate(httpSession).getOperatorInfo().getInstitutionNumber() : organNumber);
        return ResponseData.success().setData(userDTOs);
    }


    @PostMapping("/assignUserAffiliates/{uname}")
    @ApiOperation(value="用户关联机构")
    public ResponseData assignUserAffiliates(@ApiParam(name="uname",value="账户名",required=true)
                                             @PathVariable String uname,
                                             @ApiParam(name="affiliates",value="关联机构编号列表",required=true)
                                             @RequestBody List<AffiliateInfoDTO> affiliates, HttpSession httpSession){
        userApplicationService.affiliate(uname, affiliates, LoginSessionInfo.generate(httpSession).getOperator());
        return ResponseData.success();
    }

    /**
     * 为角色分配资源权限
     * @return
     */
    @PostMapping("assignResourcesToUser")
    @ApiOperation(value="为用户分配独有资源权限")
    public ResponseData assignResourcesToUser(@ApiParam(name="resourcesUser",value="权限信息",required=true)
                                              @RequestBody @Validated(value = {Insert.class}) ResourcesUser resourcesUser,
                                              BindingResult result,
                                              HttpSession httpSession){
        List<?> l = Validation.getValidation(result);
        if(l.size() != 0) {
            return ResponseData.error(JSON.toJSONString(l));
        }
        userApplicationService.assignResourcesToUser(resourcesUser, LoginSessionInfo.generate(httpSession).getOperatorInfo());
        return ResponseData.success();
    }

    @GetMapping("/medical/organ")
    @ApiOperation(value="查询机构下可用的用户信息")
    public ResponseData<List<UserDTO>> searchUserOfOrgan(HttpSession httpSession){
        List<UserDTO> userDTOs = userQuery.searchUnallocatedUsers(LoginSessionInfo.generate(httpSession).getOperatorInfo().getInstitutionNumber());
        return ResponseData.success().setData(userDTOs);
    }

}
